<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>vue 计算属性</title>
  <style>
    .good-list {
      border: 1px solid red;
    }

    .good-item {
      height: 50px;
      line-height: 50px;
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      align-items: center;
      border-bottom: 1px solid gray;
    }
  </style>
</head>

<body>
  <div id="app">
    <div>
      <h1>购物车</h1>
      <button type="button" @click="addGoodHandler"> Good</button>
      <div class="good-list">
        <div class="good-item">
          <div>序号</div>
          <div>商品名称</div>
          <div>单价</div>
          <div>数量</div>
          <div>小计</div>
        </div>
        <div class="good-item" v-for="(obj,index) in list" :key="obj.id">
          <div>{{index + 1}}</div>
          <div>{{obj.name}}</div>
          <div>{{obj.price}}</div>
          <div>{{obj.count}}</div>
          <div>{{(obj.count * obj.price).toFixed(2)}}</div>
        </div>


        <div class="good-item">
          <div>总计：</div>
          <div>{{sum}}</div>
        </div>
      </div>
    </div>
  </div>
  <script src="./vue.js"></script>
  <script>
    var vm = new Vue( {
      el: "#app",
      data: {
        list: [
          { id: 1, name: '李子', price: 8.3, count: 3 },
          { id: 2, name: '苹果', price: 7.7, count: 5 },
        ]
      },
      // 计算属性，写在 computed选项里面； 每一个计算属性的方法，都是一个函数，它在html中，做文本插值。不是调用函数！
      // 计算属性，去监听它依赖的这个变量，当变量改变时，就会自动重新执行函数里面的代码。并重新返回一个新的值去渲染页面。
      computed: {
        sum () {
          let sumPrice = 0;
          this.list.forEach( el => {
            sumPrice += el.price * el.count;

          } );

          return sumPrice.toFixed( 2 );

        }
      },
      methods: {
        addGoodHandler () {
          this.list.push( { id: 3, name: '洪苹果', price: 1.7, count: 5 } )
        }
      }
    } )
  </script>
</body>

</html>